package org.jsola.hr.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.jsola.core.Page;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.INewsTypeDAO;
import org.jsola.hr.dto.*;
import org.jsola.hr.entity.NewsTypeDO;
import org.jsola.hr.query.NewsTypeQuery;
import org.jsola.hr.service.INewsFileService;
import org.jsola.hr.service.INewsGroupService;
import org.jsola.hr.service.INewsInfoService;
import org.jsola.hr.service.INewsTypeService;
import org.jsola.hr.vo.NewsInfoVO;
import org.jsola.hr.vo.NewsTypeListVO;
import org.jsola.hr.vo.NewsTypeVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.util.HtmlUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 官网信息的类型
 *
 * @author zhr
 */
@Service("hrNewsTypeServiceImpl")
public class NewsTypeServiceImpl implements INewsTypeService {

    @Autowired
    private INewsTypeDAO newsTypeDAO;

    @Autowired
    private INewsInfoService newsInfoService;

    @Autowired
    private INewsGroupService newsGroupService;

    @Autowired
    private INewsFileService newsFileService;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public NewsTypeVO save(NewsTypeAddDTO newsTypeAddDTO, TokenUser tokenUser) {
        // 转DO
        NewsTypeDO newsTypeDO = newsTypeAddDTO.to(NewsTypeDO.class);
        // 保存
        newsTypeDO = save(newsTypeDO, "default", tokenUser.getUserId());
        return newsTypeDO.to(NewsTypeVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(NewsTypeUpdateDTO newsTypeUpdateDTO, TokenUser tokenUser) {
        //转DO
        NewsTypeDO newsTypeDO = newsTypeUpdateDTO.to(NewsTypeDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(newsTypeDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... newsTypeIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) newsTypeIds);
    }


    @Override
    public NewsTypeVO selectById(String newsTypeId, String siteId) {
        NewsTypeDO newsTypeDO = selectDOById(newsTypeId, siteId);
        if (newsTypeDO == null) {
            return null;
        }
        return newsTypeDO.to(NewsTypeVO.class);
    }

    @Override
    public List<NewsTypeListVO> select(NewsTypeQuery newsTypeQuery, String siteId) {
        List<NewsTypeDO> newsTypeDOList = selectDO(newsTypeQuery, siteId);
        if(CollectionUtils.isEmpty(newsTypeDOList)) {
            return newsTypeDOList == null ? null : new ArrayList<>();
        }
        return newsTypeDOList.stream()
                .map(newsTypeDO -> newsTypeDO.to(NewsTypeListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(NewsTypeQuery newsTypeQuery, String siteId) {
        Example example = buildExample(newsTypeQuery,siteId);
        return newsTypeDAO.selectCountByExample(example);
    }

    @Override
    public Page<NewsTypeListVO> selectPage(NewsTypeQuery newsTypeQuery, String siteId) {
        Example example = buildExample(newsTypeQuery,siteId);
        Page<NewsTypeDO> page = newsTypeDAO.selectPageByExample(example,
                newsTypeQuery.getPageNo(),
                newsTypeQuery.getPageSize());

        return page.to(NewsTypeListVO.class);
    }

    @Override
    public NewsTypeDO selectDOById(String newsTypeId, String siteId) {
        return listById(newsTypeId, "default");
    }

    @Override
    public List<NewsTypeDO> selectDO(NewsTypeQuery newsTypeQuery, String siteId) {
        Example example = buildExample(newsTypeQuery,siteId);
        return newsTypeDAO.selectByExample(example);
    }

    @Override
    public Page<NewsTypeListVO> selectPageNewsType(NewsTypeQuery newsTypeQuery) {
        PageInfo<NewsTypeListVO> pageInfo = PageHelper.startPage(newsTypeQuery.getPageNo(), newsTypeQuery.getPageSize()).doSelectPageInfo(()
                -> newsTypeDAO.selectNewsType(newsTypeQuery));
        Page<NewsTypeListVO> objectPage = new Page<>(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), (int) pageInfo.getTotal());
        return objectPage.to(NewsTypeListVO.class);
    }

    @Override
    public Integer deleteTypeAndInfoById(String[] id) {
        List<String> list = new ArrayList<>();
        Collections.addAll(list, id);
        Integer integer = newsTypeDAO.updateTypeById(list);
        Integer integer1 = newsTypeDAO.updateInfoById(list);
        return integer + integer1;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public NewsTypeVO insertNewsTypeAndInfo(NewsTypeAddDTO newsTypeAddDTO, TokenUser tokenUser) {
        newsTypeAddDTO.setNewsGroupId(newsGroupService.selectGroupByCode(newsTypeAddDTO.getNewsGroupCode()));
        String name = HtmlUtils.htmlUnescape(newsTypeAddDTO.getName());
        newsTypeAddDTO.setName(name);
        NewsTypeVO newsTypeVO = this.save(newsTypeAddDTO, tokenUser);
        NewsInfoAddDTO newsInfoAddDTO = newsTypeAddDTO.getNewsInfoAddDTO();
        newsInfoAddDTO.setNewsTypeId(newsTypeVO.getId());
        newsInfoAddDTO.setIsPush(true);
        if (newsTypeAddDTO.getPushDate() != null) {
            newsInfoAddDTO.setPushDate(newsTypeAddDTO.getPushDate());
        } else {
            newsInfoAddDTO.setPushDate(new Date());
        }
        newsInfoAddDTO.setPushUserId(tokenUser.getUserId());
        String contentHasStyle = HtmlUtils.htmlUnescape(newsInfoAddDTO.getContentHasStyle());
        String content = HtmlUtils.htmlUnescape(newsInfoAddDTO.getContent());
        //content = content.replaceAll("&nbsp;", " ");
        //contentHasStyle = contentHasStyle.replaceAll("&nbsp;", " ");
        newsInfoAddDTO.setContentHasStyle(contentHasStyle);
        newsInfoAddDTO.setContent(content);
        String title = HtmlUtils.htmlUnescape(newsInfoAddDTO.getTitle());
        //title = title.replaceAll("&nbsp;", " ");
        newsInfoAddDTO.setTitle(title);
        NewsInfoVO newsInfoVO = newsInfoService.save(newsInfoAddDTO, tokenUser);
        if (!CollectionUtils.isEmpty(newsTypeAddDTO.getNewsFileAddDTOList())) {
            newsTypeAddDTO.getNewsFileAddDTOList().forEach(bean -> {
                bean.setNewsInfoId(newsInfoVO.getId());
                newsFileService.save(bean, tokenUser);
            });
        }
        return newsTypeVO;
    }

    @Override
    public Integer updateNewsTypeAndInfo(NewsInfoUpdateDTO newsInfoUpdateDTO, TokenUser tokenUser) {
        String title = HtmlUtils.htmlUnescape(newsInfoUpdateDTO.getTitle());
        //title = title.replaceAll("&nbsp;", " ");
        newsTypeDAO.updateTypeNameById(title, newsInfoUpdateDTO.getId());
        newsInfoUpdateDTO.setTitle(title);
        String contentHasStyle = HtmlUtils.htmlUnescape(newsInfoUpdateDTO.getContentHasStyle());
        String content = HtmlUtils.htmlUnescape(newsInfoUpdateDTO.getContent());
        //content = content.replaceAll("&nbsp;", " ");
        //contentHasStyle = contentHasStyle.replaceAll("&nbsp;", " ");
        newsInfoUpdateDTO.setContentHasStyle(contentHasStyle);
        newsInfoUpdateDTO.setContent(content);
        if (!CollectionUtils.isEmpty(newsInfoUpdateDTO.getNewsFileUpdateDTOList())) {
            String id = newsTypeDAO.selectInfoByTypeId(newsInfoUpdateDTO.getId());
            newsTypeDAO.updateFileByNewsInfoId(id);
            newsInfoUpdateDTO.getNewsFileUpdateDTOList().forEach(bean -> {
                NewsFileAddDTO newsFileAddDTO = new NewsFileAddDTO();
                newsFileAddDTO.setName(bean.getName());
                newsFileAddDTO.setUrl(bean.getUrl());
                newsFileAddDTO.setSort(bean.getSort());
                newsFileAddDTO.setNewsInfoId(id);
                newsFileService.save(newsFileAddDTO, tokenUser);
            });
        }
        return newsTypeDAO.updateInfoBeanById(newsInfoUpdateDTO);
    }

    /**
     * 根据查询参数，构建example

     * @param newsTypeQuery 查询参数
     * @param siteId 所属站点id
     * @return example
     */
    private Example buildExample(NewsTypeQuery newsTypeQuery, String siteId) {
        Example example = new Example(NewsTypeDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", "default");
        if (newsTypeQuery.getNewsGroupId() != null) {
            example.and().andEqualTo("newsGroupId", newsTypeQuery.getNewsGroupId());
        }
        if (newsTypeQuery.getCode() != null) {
            example.and().andEqualTo("code", newsTypeQuery.getCode());
        }
        if (newsTypeQuery.getName() != null) {
            example.and().andEqualTo("name", newsTypeQuery.getName());
        }
        // 排序
        ExampleKit.setExampleOrder(example,newsTypeQuery.getOrders());
        return example;
    }
}




